package cn.iocoder.yudao.module.strategyPlan.service.strategyPlan;

import cn.iocoder.yudao.module.strategy.dal.dataobject.strategy.StrategyDO;
import cn.iocoder.yudao.module.strategy.service.strategy.StrategyService;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.module.strategyPlan.controller.admin.strategyPlan.vo.*;
import cn.iocoder.yudao.module.strategyPlan.dal.dataobject.strategyPlan.StrategyPlanDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.strategyPlan.convert.strategyPlan.StrategyPlanConvert;
import cn.iocoder.yudao.module.strategyPlan.dal.mysql.strategyPlan.StrategyPlanMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.strategyPlan.enums.ErrorCodeConstants.*;

/**
 * 企业战略-计划 Service 实现类
 *
 * @author huangjunwei
 */
@Service
@Validated
@Slf4j
public class StrategyPlanServiceImpl implements StrategyPlanService {

    @Resource
    private StrategyPlanMapper Mapper;

    @Resource
    private StrategyService strategyService;

    @Resource
    private DeptService deptService;
    
    @Resource
    private AdminUserService adminUserService;

    @Override
    public Long create(StrategyPlanCreateReqVO createReqVO) {
        // 插入
        StrategyPlanDO strategyPlanDO = StrategyPlanConvert.INSTANCE.convert(createReqVO);
        Mapper.insert(strategyPlanDO);
        // 返回
        return strategyPlanDO.getId();
    }

    @Override
    public void update(StrategyPlanUpdateReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        StrategyPlanDO updateObj = StrategyPlanConvert.INSTANCE.convert(updateReqVO);
        Mapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        Mapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (Mapper.selectById(id) == null) {
            throw exception(NOT_EXISTS);
        }
    }

    @Override
    public StrategyPlanDO get(Long id) {
        return Mapper.selectById(id);
    }

    /**
     * 获得企业战略-计划
     *
     * @param id 编号
     * @return 企业战略-计划
     */
    @Override
    public StrategyPlanRespVO getStrategyPlanRespVO(Long id) {
        StrategyPlanDO strategyPlanDO = this.get(id);
        StrategyPlanRespVO strategyPlanRespVO = StrategyPlanConvert.INSTANCE.convert(strategyPlanDO);
        this.rebuildStrategyPlanRespVO(strategyPlanRespVO);
        return strategyPlanRespVO;
    }

    private void rebuildStrategyPlanRespVO(StrategyPlanRespVO strategyPlanRespVO) {
        if (strategyPlanRespVO == null) {
            return;
        }
        //组织
        DeptDO dept = deptService.getDept(strategyPlanRespVO.getOrganizationId());
        if (dept != null) {
            strategyPlanRespVO.setOrganizationName(dept.getName());
        }

        //战略
        StrategyDO strategyDO = strategyService.get(strategyPlanRespVO.getStrategyId());
        if (strategyDO != null) {
            strategyPlanRespVO.setOrganizationName(strategyDO.getStrategyName());
        }
        strategyPlanRespVO.setStrategyName(strategyDO.getStrategyName());

        //创建者姓名
        if (StringUtils.isNotBlank(strategyPlanRespVO.getCreator())) {
            AdminUserDO adminUserDO = adminUserService.getUser(Long.valueOf(strategyPlanRespVO.getCreator()));
            if (adminUserDO != null) {
                strategyPlanRespVO.setCreatorName(adminUserDO.getNickname());
            }
        }
        //更新者姓名
        if (StringUtils.isNotBlank(strategyPlanRespVO.getUpdater())) {
            AdminUserDO adminUserDO = adminUserService.getUser(Long.valueOf(strategyPlanRespVO.getUpdater()));
            if (adminUserDO != null) {
                strategyPlanRespVO.setUpdaterName(adminUserDO.getNickname());
            }
        }
        //决策者姓名
        AdminUserDO adminUserDO = adminUserService.getUser(strategyPlanRespVO.getDecisionUser());
        if (adminUserDO != null) {
            strategyPlanRespVO.setDecisionUserName(adminUserDO.getNickname());
        }
    }

    @Override
    public List<StrategyPlanDO> getList(Collection<Long> ids) {
        return Mapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<StrategyPlanDO> getPage(StrategyPlanPageReqVO pageReqVO) {
        return Mapper.selectPage(pageReqVO);
    }

    /**
     * 获得企业战略-计划分页
     *
     * @param pageReqVO 分页查询
     * @return 企业战略-计划分页
     */
    @Override
    public PageResult<StrategyPlanRespVO> getPageStrategyPlanRespVO(StrategyPlanPageReqVO pageReqVO) {
        PageResult<StrategyPlanDO> strategyPlanDOPageResult = this.getPage(pageReqVO);

        PageResult<StrategyPlanRespVO> strategyPlanRespVOPageResult = StrategyPlanConvert.INSTANCE.convertPage(strategyPlanDOPageResult);
        if (strategyPlanRespVOPageResult != null && !CollectionUtils.isEmpty(strategyPlanRespVOPageResult.getList())) {
            List<StrategyPlanRespVO> strategyPlanRespVOList = strategyPlanRespVOPageResult.getList();
            this.rebuildStrategyPlanRespVOList(strategyPlanRespVOList);
        }
        return strategyPlanRespVOPageResult;
    }

    private void rebuildStrategyPlanRespVOList(List<StrategyPlanRespVO> strategyPlanRespVOList) {
        /** 组织  */
        Set<Long> deptIdSet = strategyPlanRespVOList.stream()
                .filter(Objects::nonNull)
                .map(StrategyPlanBaseVO::getOrganizationId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查组织
        List<DeptDO> deptDOList = deptService.getDeptList(deptIdSet);
        Map<Long, DeptDO> deptDOMap = new HashMap<>();
        deptDOList.forEach(item -> {
            deptDOMap.put(item.getId(), item);
        });
        //设置组织名称
        for (StrategyPlanRespVO strategyPlanRespVO : strategyPlanRespVOList) {
            if (deptDOMap.get(strategyPlanRespVO.getOrganizationId()) != null) {
                strategyPlanRespVO.setOrganizationName(deptDOMap.get(strategyPlanRespVO.getOrganizationId()).getName());
            }
        }

        /** 战略 */
        Set<Long> strategyIdLongSet = strategyPlanRespVOList.stream()
                .filter(Objects::nonNull)
                .map(StrategyPlanBaseVO::getStrategyId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        //查战略
        List<StrategyDO> strategyDOList = strategyService.getList(strategyIdLongSet);
        Map<Long, StrategyDO> strategyDOMap = new HashMap<>();
        strategyDOList.forEach(item -> {
            strategyDOMap.put(item.getId(), item);
        });
        //设置战略名称
        for (StrategyPlanRespVO strategyPlanRespVO : strategyPlanRespVOList) {
            if (strategyDOMap.get(strategyPlanRespVO.getStrategyId()) != null) {
                strategyPlanRespVO.setStrategyName(strategyDOMap.get(strategyPlanRespVO.getStrategyId()).getStrategyName());
            }
        }

        /** 用户 */
        //创建者+更新者+决策者
        Set<String> userIdStringSet = strategyPlanRespVOList.stream()
                .filter(Objects::nonNull)
                .flatMap(item -> {
                    return Stream.of(item.getCreator(), item.getUpdater(), String.valueOf(item.getDecisionUser()));
                })
                .filter(id -> StringUtils.isNotBlank(id))
                .collect(Collectors.toSet());
        //将Set<String>转换为Set<Long>
        Set<Long> userIdLongSet = userIdStringSet.stream()
                .map(userIdString -> {
                    try {
                        return Long.parseLong(userIdString);
                    } catch (Exception e) {
                        log.error("用户相关数据异常，strategyPlanRespVOList：" + JSON.toJSONString(strategyPlanRespVOList), e);
                        return null;
                    }
                })
                .filter(Objects::nonNull) // 过滤掉空的
                .collect(Collectors.toSet());
        //查用户
        List<AdminUserDO> adminUserDOList = adminUserService.getUserList(userIdLongSet);
        Map<Long, AdminUserDO> adminUserDOMap = new HashMap<>();
        adminUserDOList.forEach(item -> {
            adminUserDOMap.put(item.getId(), item);
        });
        //设置用户姓名
        for (StrategyPlanRespVO strategyPlanRespVO : strategyPlanRespVOList) {
            AdminUserDO adminUserDOFromMap = null;
            //创建者
            adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanRespVO.getCreator()));
            if (adminUserDOFromMap != null) {
                strategyPlanRespVO.setCreatorName(adminUserDOFromMap.getNickname());
            }
            //更新者
            adminUserDOFromMap = adminUserDOMap.get(Long.valueOf(strategyPlanRespVO.getUpdater()));
            if (adminUserDOFromMap != null) {
                strategyPlanRespVO.setUpdaterName(adminUserDOFromMap.getNickname());
            }
            //决策者
            adminUserDOFromMap = adminUserDOMap.get(strategyPlanRespVO.getDecisionUser());
            if (adminUserDOFromMap != null) {
                strategyPlanRespVO.setDecisionUserName(adminUserDOFromMap.getNickname());
            }
        }
    }

    @Override
    public List<StrategyPlanDO> getList(StrategyPlanExportReqVO exportReqVO) {
        return Mapper.selectList(exportReqVO);
    }

}
